import { PaginationParams } from '@/types';

/**
 * 从请求参数中提取分页信息
 */
export function getPaginationParams(
  page: number = 1,
  pageSize: number = 20,
): PaginationParams {
  const validPage = Math.max(1, page);
  const validPageSize = Math.min(Math.max(1, pageSize), 100);
  const offset = (validPage - 1) * validPageSize;

  return {
    page: validPage,
    pageSize: validPageSize,
    offset,
    limit: validPageSize,
  };
}

/**
 * 从 Host 头中提取子域名
 */
export function extractSubdomain(host: string, baseDomain: string): string | null {
  if (!host) return null;

  // 移除端口号
  const hostname = host.split(':')[0];
  
  if (!hostname) return null;

  // 检查是否包含基础域名
  if (!hostname.endsWith(baseDomain)) {
    return null;
  }

  // 提取子域名
  const subdomain = hostname.slice(0, -baseDomain.length - 1);

  // 如果子域名为空或包含 www，返回 null
  if (!subdomain || subdomain === 'www') {
    return null;
  }

  return subdomain;
}

/**
 * 延迟函数
 */
export function delay(ms: number): Promise<void> {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

/**
 * 深度合并对象
 */
export function deepMerge<T extends Record<string, any>>(target: T, ...sources: Partial<T>[]): T {
  if (!sources.length) return target;

  const source = sources.shift();
  if (!source) return target;

  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach((key) => {
      const sourceValue = source[key];
      const targetValue = (target as any)[key];

      if (isObject(sourceValue) && isObject(targetValue)) {
        (target as any)[key] = deepMerge({ ...targetValue }, sourceValue);
      } else {
        (target as any)[key] = sourceValue;
      }
    });
  }

  return deepMerge(target, ...sources);
}

/**
 * 检查是否为对象
 */
function isObject(item: any): item is Record<string, any> {
  return item && typeof item === 'object' && !Array.isArray(item);
}

/**
 * 安全的 JSON 解析
 */
export function safeJsonParse<T = any>(json: string, defaultValue: T): T {
  try {
    return JSON.parse(json) as T;
  } catch {
    return defaultValue;
  }
}

/**
 * 移除对象中的 undefined 和 null 值
 */
export function removeNullish<T extends Record<string, any>>(obj: T): Partial<T> {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (value !== null && value !== undefined) {
      acc[key] = value;
    }
    return acc;
  }, {} as Record<string, any>) as Partial<T>;
}


